#!/usr/bin/env bash

CLOUD=$1
echo "Upgrade nginx script, CLOUD=$CLOUD"

# Setup nginx configuration.
if [[ ! -d /etc/nginx/default.d ]]; then
  exit 0
fi
if [[ ! -d /etc/nginx/conf.d ]]; then
  exit 0
fi

# Migrate the previous SSL files.
if [[ ! -f containers/ssl/nginx.key && -f /etc/nginx/ssl/nginx.key ]]; then
  mkdir -p containers/ssl &&
  ln -sf "$(readlink -f /etc/nginx/ssl/nginx.key)" containers/ssl/nginx.key &&
  ln -sf "$(readlink -f /etc/nginx/ssl/nginx.crt)" containers/ssl/nginx.crt
  if [[ $? -ne 0 ]]; then echo "Setup SSL/TLS files failed"; exit 1; fi
fi

# Migrate the previous dynamic config.
if [[ -f containers/conf/nginx.dynamic.conf && ! -f containers/conf/default.d/nginx.dynamic.conf ]]; then
  mv containers/conf/nginx.dynamic.conf containers/conf/default.d/nginx.dynamic.conf
  if [[ $? -ne 0 ]]; then echo "Setup nginx dynamic failed"; exit 1; fi
fi

# Overwrite the default nginx config.
rm -f /etc/nginx/nginx.conf &&
ln -sf "$(pwd)/containers/conf/nginx.conf" /etc/nginx/nginx.conf && echo "Refresh nginx.conf ok"
if [[ $? -ne 0 ]]; then echo "Refresh nginx.conf failed"; exit 1; fi

# For DO Ubuntu20, use www-data as nginx user.
if [[ $CLOUD == DO ]];  then
  echo "Switch to user www-data for nginx" &&
  sed -i "s/user nginx;/user www-data;/g" /etc/nginx/nginx.conf
  if [[ $? -ne 0 ]]; then echo "Setup nginx.conf failed"; exit 1; fi
fi

# Build the mgmt/containers/conf/conf.d/nginx.vhost.conf
bash auto/setup_vhost
if [[ $? -ne 0 ]]; then echo "Build nginx vhost failed"; exit 1; fi

# For nginx server config
rm -f /etc/nginx/conf.d/nginx.vhost.conf /etc/nginx/conf.d/server.conf &&
ln -sf "$(pwd)/containers/conf/conf.d/nginx.vhost.conf" /etc/nginx/conf.d/vhost.conf
if [[ $? -ne 0 ]]; then echo "Refresh nginx vhost.conf failed"; exit 1; fi

# Reload nginx service.
systemctl reload nginx && echo "Reload nginx ok"
if [[ $? -ne 0 ]]; then echo "Reload nginx failed"; exit 1; fi

